<template>
  <div class="wangge-chart">
    <el-row :gutter="20" align="middle" style="margin-top: -16px">
      <el-col :span="15">
        <div class="wangge-chart-title">随销达标人数及占比</div>
      </el-col>
      <el-col :span="4">
        <el-select
          v-model="selectedDistrict"
          placeholder="选择区县"
          style="width: 100%"
          @change="handleDistrictChange"
        >
          <el-option
            v-for="district in districtOptions"
            :key="district.value"
            :label="district.label"
            :value="district.value"
          />
        </el-select>
      </el-col>
      <el-col :span="4">
        <!-- 年份选择器 -->
        <el-select
          v-model="selectedYear"
          placeholder="选择年份"
          style="width: 100%"
          @change="handleYearChange"
        >
          <el-option
            v-for="year in yearOptions"
            :key="year.value"
            :label="year.label"
            :value="year.value"
          />
        </el-select>
      </el-col>
      <div class="chart-description">注：随销加新装占总收入比例大于50</div>
    </el-row>
    <div
      ref="wanggeChart"
      class="wangge-chart-container"
      style="height: 420px"
    />
  </div>
</template>

<script>
import { ElDatePicker, ElRow, ElCol, ElSelect, ElOption } from "element-plus";
import * as echarts from "echarts";
import { salaryRatiosByDistrictAndTime } from "@/api/dwxc/income";

export default {
  components: {
    ElRow,
    ElCol,
    ElSelect,
    ElOption,
  },
  props: {
  },
  data() {
    return {
      selectedYear: new Date().getFullYear(), // 默认选择当前年份
      selectedDistrict: "全市", // 选中的区县，默认选择全市
      districtOptions: [
        { label: "全市", value: "全市" },
        { label: "浔阳区", value: "浔阳区" },
        { label: "濂溪区", value: "濂溪区" },
        { label: "柴桑区", value: "柴桑区" },
        { label: "瑞昌市", value: "瑞昌市" },
        { label: "共青城", value: "共青城" },
        { label: "庐山市", value: "庐山市" },
        { label: "武宁县", value: "武宁县" },
        { label: "修水县", value: "修水县" },
        { label: "永修县", value: "永修县" },
        { label: "德安县", value: "德安县" },
        { label: "都昌县", value: "都昌县" },
        { label: "湖口县", value: "湖口县" },
        { label: "彭泽县", value: "彭泽县" },
      ],
      yearOptions: this.generateYearOptions(), // 生成年份选项
      chartData: null,
    };
  },
  mounted() {
    this.initializeChart();
  },
  methods: {
    // 生成年份选项（从2020年到当前年份）
    generateYearOptions() {
      const currentYear = new Date().getFullYear();
      const years = [];
      for (let year = 2020; year <= currentYear; year++) {
        years.push({ label: `${year}年`, value: year });
      }
      return years;
    },

    initializeChart() {
      // 初始化时获取数据
      this.getChartData();
    },
    handleDistrictChange(district) {
      console.log("suixiaoRadios handleDistrictChange called with:", district);
      this.getChartData();
    },
    handleYearChange(year) {
      console.log("suixiaoRadios handleYearChange called with:", year);
      this.getChartData();
    },
    // 调用接口获取数据
    async getChartData() {
      try {
        // 构建请求参数
        const params = {
          district: this.selectedDistrict === "全市" ? "全市" : this.selectedDistrict,
          time: this.selectedYear
        };
        console.log('getChartData - 获取数据参数:', params);
        // 调用接口 salaryRatiosByDistrictAndTime
        const response = await salaryRatiosByDistrictAndTime(params);
        console.log('getChartData - 接口响应数据:', response);
        if (response) {
          this.chartData = response;
          this.initWanggeChart(this.$refs.wanggeChart, response);
        } else {
          this.$message.warning("后端返回数据为空，使用默认数据显示");
          this.initWanggeChart(this.$refs.wanggeChart, null);
        }
      } catch (error) {
        console.error("获取数据失败：", error);
        this.$message.error("获取数据失败：" + error.message);
        this.initWanggeChart(this.$refs.wanggeChart, null);
      }
    },
    // 处理图表数据
    processChartData(data) {
      // 初始化12个月的数据
      const months = Array.from({ length: 12 }, (_, i) => `${i + 1}月`);
      const maintainersData = Array(12).fill(0);
      const percentageData = Array(12).fill(0);
      
      // 填充实际数据
      if (data && Array.isArray(data)) {
        data.forEach(item => {
          const month = parseInt(item.time.split('-')[1]);
          if (month >= 1 && month <= 12) {
            maintainersData[month - 1] = item.totalMaintainers;
            percentageData[month - 1] = item.salaryPercentage;
          }
        });
      }
      
      return {
        months,
        maintainersData,
        percentageData
      };
    },
     initWanggeChart(chartRef, rawData) {
      if (!chartRef) return;

      if (chartRef._echarts_instance_) {
        chartRef._echarts_instance_.dispose();
      }

      const chart = echarts.init(chartRef);
      const processedData = this.processChartData(rawData);

      chart.setOption({
        title: {
          
          left: 'center'
        },
        grid: {
          top: "10%",
          left: "3%",
          right: "3%",
          bottom: "10%",
          containLabel: true,
          borderWidth: 0,
          show: false
        },
        xAxis: {
          type: "category",
          data: processedData.months,
          axisLabel: {
            fontSize: 12,
            fontWeight: "normal",
            color: "#6A6A6A",
            fontFamily: "Arial, sans-serif"
          }
        },
        yAxis: [
          {
            type: "value",
            name: "人数",
            min: 0
          },
          {
            type: "value",
            name: "占比(%)",
            axisLabel: {
              formatter: "{value}%"
            },
            // 添加虚线配置
            splitLine: {
              show: true,
              lineStyle: {
                type: "dashed", // 改为虚线
                color: "#E6E6E6", // 保持原有颜色
                width: 1 // 可以根据需要调整线宽
              }
            }
          }
        ],
        series: [
          {
            name: "达标代维人员数",
            data: processedData.maintainersData,
            type: "bar",
            itemStyle: {
              color: "#73C0DE"
            },
            label: {
              show: true,
              position: "top",
              fontSize: 12,
              color: "#333",
              formatter: function (params) {
                if (params.value === 0) {
                  return "";
                }
                return params.value;
              }
            }
          },
          {
            name: "总人数占比",
            data: processedData.percentageData,
            type: "line",
            yAxisIndex: 1,
            smooth: true,
            symbol: "circle",
            symbolSize: 6,
            lineStyle: {
              width: 2,
              color: "#FAC858"
            },
            itemStyle: {
              color: "#FF4500",
              borderColor: "#fff",
              borderWidth: 2
            },
            label: {
              show: false,
              formatter: function (params) {
                return params.value.toFixed(1) + "%";
              }
            }
          }
        ],
        tooltip: {
          trigger: "axis",
          formatter: function (params) {
            let result = `${params[0].name}<br/>`;
            params.forEach(function (item) {
              if (item.seriesIndex === 0) {
                result += `${item.marker} ${item.seriesName}: ${item.value}人<br/>`;
              } else if (item.seriesIndex === 1) {
                result += `${item.marker} ${item.seriesName}: ${item.value.toFixed(2)}%`;
              }
            });
            return result;
          }
        }
      });

      setTimeout(() => {
        chart.resize();
      }, 100);

      chartRef._echarts_instance_ = chart;
    }
  }
};
</script>

<style scoped>
.chart-description {
  font-size: 12px; /* 注释的字号 */
  color: #999; /* 注释的颜色 */
}
.wangge-chart {
  padding: 20px;
}
.wangge-chart-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
}
.wangge-chart-container {
  height: 400px;
}
</style>
